<template>
  <div class="home">
    <!-- 我的待办 -->
    <div class="mytodo">
      <div class="mytodo-title">
        <h2>首页</h2>
        <!-- 添加文件按钮 -->
        <div class="button-box">
          <el-button class="add-obj" style="margin-right:20px" @click="checkHistory"><span style="display:flex">
              <svg-icon icon-class="icon-adding" style="margin-right:1rem;"></svg-icon>
              <h3>查看历史文件</h3>
              </span></el-button>
          <el-button v-if="isMultiple == true" class="add-obj" style="margin-right:20px" @click="multiDownload"><span style="display:flex">
              <svg-icon icon-class="icon-adding" style="margin-right:1rem;"></svg-icon>
              <h3>批量下载</h3>
              </span></el-button>
          <el-upload
              action=""
              :show-file-list="false"
              :multiple="true"
              :before-upload="beforeUpload">
                <el-button size="small" class="add-obj">
                  <span style="display:flex">
                  <svg-icon icon-class="icon-adding" style="margin-right:1rem;"></svg-icon>
                  <h3>添加文件</h3>
                  </span>
                </el-button>
              </el-upload>
        </div>
      </div>
      <todo-content ref="child" @isMultiple="appendMultiple" @selectFileList="selectFiles" :tbData="uploadFilesList" :TransferSuccess="TransferSuccess" :isTransfer="isTransfer"></todo-content>
    </div>
    <!-- 右侧 -->
    <div class="others">
      <!-- 文件转换概览 -->
      <div class="status-bar">
        <div class="status-bar-title">
          <h2>转换概览</h2>
        </div>
        <status-bar :tbData="uploadFilesList" @isTransfer="changeState" @DataChange="changeProcess" @TransferSuccess="changeTransferState"></status-bar>
      </div>
      
    </div>
  </div>
</template>

<script>
// 文件列表
import TodoContent from "../components/TodoContent.vue";
// 进度条
import StatusBar from "../components/StatusBar.vue";

let config = {
               headers:{"Authorization": localStorage.getItem("token")}
           };

export default {
  name: "MyTodo",
  components: {
    TodoContent,
    StatusBar,
  },
  data() {
    return {
      uploadFilesList:[],
      selectFileList:[],
      isMultiple:false,
      isTransfer:false,
      TransferSuccess:'error'
    };
  },
  created:function(){
    // this.loadFileList()
    this.onsuccess()
  },
  computed: {
  },
  methods: {
    //查看历史文件记录
    checkHistory(){
      this.$router.push({path:'/HistoryFIleList'})
    },
    //批量下载
    multiDownload(){
      this.selectFileList.forEach(element=>{
        // console.log("下载："+element['id'])
        this.$refs.child.downLoad(element['id'])
      })
    },

    selectFiles(arr){
      // console.log(arr)
      this.selectFileList = arr
    },
    appendMultiple(state){
      // console.log(state)
      this.isMultiple = state
    },
    changeTransferState(state){
      // console.log(state)
      this.TransferSuccess = state
    },
    changeProcess(data){
      // console.log(data[0].transferProcess)
      this.uploadFilesList = data
      // console.log(this.uploadFilesList)
    },
    changeState(state){
      // console.log(state)
      this.isTransfer = state
    },

    //初始化加载列表
    loadFileList(){
      this.$axios
      .get('/file/getOutputFileList',config)
      .then(successResponse=>{
        let res = successResponse.data.data
        // console.log(res[0])
        var dataList = []
        res.forEach(element => {
          // console.log(element['fileName'])
          let jsonData = {}
          jsonData['id'] = element['id']
          jsonData['name'] = element['fileName']
          let size =parseInt(element['fileSize'] / 1024)
          // console.log(size)
          if(size >= 1024){
            jsonData['size'] = parseInt(size / 1024) + ' MB'
          }else{
            jsonData['size'] = size + ' KB'
          }
          jsonData['status'] = element['fileState'] == null ? 'success':element['fileState']
          dataList.push(jsonData)
        });
        // console.log(dataList)
        this.uploadFilesList = dataList
        // console.log(this.uploadFilesList)
      })
    },
    //上传成功后得到
    onsuccess(){
      this.$axios
      .get('/file/getUploadFileList',config)
      .then(response=>{
        let res = response.data.data
        // console.log(res[0])
        var dataList = []
        res.forEach(element => {
          console.log(element['fileName'])
          let jsonData = {}
          jsonData['id'] = element['id']
          jsonData['name'] = element['fileName']
          let size =parseInt(element['fileSize'] / 1024)
          // console.log(size)
          if(size >= 1024){
            jsonData['size'] = parseInt(size / 1024) + ' MB'
          }else{
            jsonData['size'] = size + ' KB'
          }
          jsonData['status'] = element['fileState'] == null ? 'success':element['fileState']==0?'success':'error'
          jsonData['transferProcess'] = 0
          jsonData['transferStatus'] = 'transfering'
          dataList.push(jsonData)
        });
        // console.log(dataList)
        this.uploadFilesList = dataList
        this.isTransfer = false;
      })
    },
    beforeUpload(file) {
      const fileList = {}
      for (const key in file) {
        if(key == 'size'){
          let size = parseInt(file[key]) / 1024

          if(size >= 1024){
            fileList[key] = parseInt(file[key] / 1024 / 1024) + ' MB'
          }else{
            fileList[key] = parseInt(file[key] / 1024) + ' KB' 
          }
          console.log(fileList[key])
        }else{
          fileList[key] = file[key]
        }
        
      }
      // status:uploading、success、error 文件上传状态
      // progress 文件上传进度
      this.uploadFilesList.push({ ...fileList, progress: 0,transferProcess: 0, status: 'uploading',transferStatus:'transfering' })
      // console.log(this.uploadFilesList)
      this.httpRequest(file, parms => {
        this.showProgress(fileList, parms)
      })
      // 阻止 el-upload的默认上传

      this.TransferSuccess = 'error'
      setTimeout(() => {
        this.onsuccess()
        
        // this.$router.go(0)
      }, 500);
      return false
    },
    showProgress(file, parms) {
      const { progress, status } = parms
      const arr = [...this.uploadFilesList].map(items => {
        if (items.uid === file.uid) {
          items.progress = progress
          items.status = status
        }
        return items
      })
      this.uploadFilesList = [...arr]
    },
    //发起异步请求
    async httpRequest(file, callback) {
        console.log(file)
        var params = new FormData()// 组合适合自己的参数
        params.append(file.name,file);
        let progress = 0
        this.$axios({
            method: 'post',
            url: '/file/upload',
            data: params,
            headers: {
            "Authorization": localStorage.getItem("token")
          },
            onUploadProgress: progressEvent => { // 获取文件上传进度 axios自带的
            progress = (progressEvent.loaded / progressEvent.total * 100) | 0
            callback({ progress, status: 'uploading' })
            }
        }).then(() => { // 成功状态
            callback({ progress, status: 'success' })
        }).catch(() => { // 失败状态
            callback({ progress, status: 'error' })
        })
        }
  },
};
</script>

<style scoped>
.home {
  display: flex;
}
/* 我的待办 */
.mytodo {
  margin: 0 2rem 0 2rem;
  width: 100%;
  min-width: 44.5rem;
  flex-grow: 1;
}
.mytodo-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 5rem;
}
.button-box {
  margin-top: 3rem;
  
  display:inline-flex;
  justify-content: flex-end;
}
.add-obj {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 9rem;
  height: 2.5rem;
  border: none;

  color: var(--BG);
  font-size: 0.75rem;
  line-height: 1rem;
  border-radius: 0.7rem;
  background-color: var(--Theme-6);
  cursor: pointer;
}
.add-obj:hover {
  background-color: var(--Theme-7);
}
.add-obj:active {
  background-color: var(--Theme-8);
}

/* 右侧 */
.others {
  display: none;
  flex-direction: column;
  margin: 0 2rem 0 1.5rem;
}
/* 状态显示 */
.status-bar {
  display: flex;
  flex-direction: column;
  height: 35rem;
  width: 22.5rem;
  margin-top: 0.2rem;
  
}
.status-bar-title {
  display: flex;
  align-items: center;
  height: 5rem;
  margin-top: 2rem;
  
}
@media screen and (min-width: 1280px) {
  .mytodo {
    width: 100%;
    min-width: 36.5rem;
    margin: 0 0 0 2rem;
  }
  .others {
    display: flex;
  }
}
</style>